// Copyright © 2009, Blake Coverett 
// Use and Redistribute Freely under the Ms-PL
// http://www.opensource.org/licenses/ms-pl.html
var html = (function(){
	var module = {};

	var $ = module.$ = function(id) { return document.getElementById(id); }

	var tags = /{([^}]*)}/g;
	var replace = module.replace = function(s, subs) {
		if (!(s instanceof String)) s += '';
		return subs ? s.replace(tags, function(m, t) { return subs[t]; }) : s;
	}

	module.marker = [];

	var internalAdd = function(parent, children, subs, results) {
		if (children === module.marker) {
			results.push(parent);
			return;
		}
		for(var i = 0, cc = children.length; i < cc; ++i) {
			child = children[i];
			if (child === module.marker) {
				results.push(parent);
			} else if (child instanceof Object && !(child instanceof Array)) {
				var tag = false;
				for(tag in child) if (child[tag] instanceof Array) break;
				if (!tag) throw "no tagname found";
				var e = document.createElement(tag);
				for(p in child)
					if (p == 'style') {
						var src = child[p], dst = e.style;
						for(var s in src)
							dst[s] = replace(src[s], subs);
					} else if (p != tag)
						e[p] = replace(child[p], subs);
				internalAdd(e, child[tag], subs, results);
				parent.appendChild(e);
			} else
				parent.appendChild(document.createTextNode(
					replace(child, subs)));
		}
	}
		
	var add = module.add = function(parent, spec, subs) {
		if (!parent) throw "no parent in html.add";
		var results = [];
		if (!(spec instanceof Array)) spec = [spec];
		internalAdd(parent, spec, subs, results);
		return results;
	};
	/* Sample Usage:
	var r = html.add(output, [
			{h1:html.marker},
			{div:[
				{span:['<'], style:{color:'{delims}'}},
				'this is {adj} {noun}',
				{span:['>'], style:{backgroundColor:'{delims}'}} 
			], align:'center'},
			{div:html.marker}
		],
		{adj:'very', noun:'cool', delims:'red'});
	r[0].innerHTML = 'Wow';
	r[1].innerHTML = 'footer';
	*/

	return module;
})();
